let code = require('../../../constant/code');
let unionManager = require('../domain/unionManager');
let userDao = require('../../../dao/userDao');
let commonDao = require('../../../dao/commonDao');
let logger = require('pomelo-logger').getLogger("logic");
let gameConfig = require('../../../gameComponent/gameConfig');
let enumeration = require('../../../constant/enumeration');
const userInfoServices = require('../../../services/userInfoServices');

module.exports = function (app) {
    return new Handler(app);
};

let Handler = function (app) {
    this.app = app;
};

//创建房间规则
Handler.prototype.addRoomRuleList = async function (msg, session, next) {


    logger.info(`[${session.uid}] add room rule list begin`);

    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }

    if (!msg.unionID || !msg.ruleName || !msg.gameType || !msg.roomRule) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        return;
    }

    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(item => item.unionID === msg.unionID);
    if (!unionInfoItem) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        return;
    }

    //盟主和管理有权限
    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, { code: code.PERMISSION_NOT_ENOUGH });
        return;
    }

    //判断盟主砖石是否足够
    // let payDiamond = gameConfig.oneUserDiamondCount(msg.roomRule.bureau, msg.roomRule.gameType);
    // let ownerUserData = await userDao.getUserDataByUid(union.getOwnerUid());
    // logger.info(`[addRoomRuleList] payDiamond = ${payDiamond} userGold = ${ownerUserData.gold}  `);

    // if (ownerUserData.gold < payDiamond) {
    //     next(null, { code: code.NOT_ENOUGH_GOLD });
    //     return;
    // }

    let code = await union.addRoomRuleList(msg.roomRule, msg.ruleName, msg.gameType);
    next(null, { code: code, msg: { unionInfo: union.getUnionInfo(session.uid), roomList: union.getUnionRoomList() } });

};

Handler.prototype.updateRoomRuleList = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID || !msg.ruleName || !msg.gameType || !msg._id || !msg.roomRule) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });

    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }

    //判断盟主砖石是否足够
    // let payDiamond = msg.roomRule.payDiamond || 0;
    let payDiamond = gameConfig.oneUserDiamondCount(msg.roomRule.bureau, msg.roomRule.gameType, msg.roomRule.maxPlayerCount);
    let ownerUserData = await userDao.getUserDataByUid(union.getOwnerUid());
    if (ownerUserData.gold <= 0 || ownerUserData.gold < payDiamond) {
        next(null, {
            code: code.NOT_ENOUGH_GOLD
        });
        return;
    } else {
        let roomRule = await union.updateRoomRuleList(msg._id, msg.roomRule, msg.ruleName, msg.gameType);
        next(null, {
            code: code.OK,
            msg: {
                roomRule
                // unionInfo: union.getUnionInfo(session.uid),
                // roomList: union.getUnionRoomList()
            }
        });
    }


};

Handler.prototype.removeRoomRuleList = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID || !msg.roomRuleID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });

    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }
    await union.removeRoomRuleList(msg.roomRuleID);
    next(null, {
        code: code.OK,
        msg: {
            roomRuleID: msg.roomRuleID,
            unionInfo: union.getUnionInfo(session.uid),
            roomList: union.getUnionRoomList()
        }
    });
};

Handler.prototype.updateUnionNotice = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID || (!msg.notice && msg.notice !== '') || msg.notice.length > 50) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });

    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }

    await union.updateUnionNotice(msg.notice);
    next(null, {
        code: code.OK,
        msg: {
            unionInfo: union.getUnionInfo(session.uid),
            roomList: union.getUnionRoomList()
        }
    });
};

Handler.prototype.updateOpeningStatus = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });

    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }

    await union.updateOpeningStatus(msg.isOpen);
    next(null, {
        code: code.OK,
        msg: {
            unionInfo: union.getUnionInfo(session.uid),
            roomList: union.getUnionRoomList()
        }
    });
};

Handler.prototype.transferUnion = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID || !msg.transferUid || msg.transferUid === session.uid) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let userData = await userDao.getUserDataByUid(msg.transferUid);
    if (!userData) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid()) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    // 转移的玩家必须在联盟中
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });
    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    await union.transferUnion(msg.transferUid);
    next(null, {
        code: code.OK,
        msg: {
            unionInfo: union.getUnionInfo(session.uid),
            roomList: union.getUnionRoomList()
        }
    });
};

Handler.prototype.updateUnionName = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID || !msg.unionName) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });

    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }
    await union.updateUnionName(msg.unionName);
    next(null, {
        code: code.OK,
        msg: {
            unionInfo: union.getUnionInfo(session.uid),
            roomList: union.getUnionRoomList()
        }
    });
};

Handler.prototype.updatePartnerNoticeSwitch = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid()) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    await union.updatePartnerNoticeSwitch(msg.isOpen);
    next(null, {
        code: code.OK
    });
};


//大厅踢出玩家dismissUser
Handler.prototype.dismissUser = async function (msg, session, next) {

    logger.info(`[dismissUser] msd = ${JSON.stringify(msg)} `);
    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }
    if (!msg.unionID || !msg.roomID || !msg.uid) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        return;
    }
    let union = await unionManager.getUnion(msg.unionID);
    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) { return ele.unionID === msg.unionID; });
    if (!unionInfoItem) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        return;
    }
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, { code: code.PERMISSION_NOT_ENOUGH });
        return;
    }
    let curCode = await union.userLeaveRoom(msg.uid, msg.roomID);

    next(null, {
        code: curCode,
        msg: {
            unionInfo: union.getUnionInfo(session.uid),
            roomList: union.getUnionRoomList()
        }
    });
}

Handler.prototype.dismissRoom = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID || !msg.roomID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let union = await unionManager.getUnion(msg.unionID);


    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });

    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }


    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }



    if (await union.dismissRoom(msg.roomID)) {
        next(null, {
            code: code.OK,
            msg: {
                unionInfo: union.getUnionInfo(session.uid),
                roomList: union.getUnionRoomList()
            }
        });
    } else {
        next(null, {
            code: code.FAIL,
            msg: {
                unionInfo: union.getUnionInfo(session.uid),
                roomList: union.getUnionRoomList()
            }
        });
    }

};

Handler.prototype.hongBaoSetting = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    try {

        let userData = await userDao.getUserDataByUid(session.uid);
        let unionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });

        if (!unionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        let union = await unionManager.getUnion(msg.unionID);
        if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        let resCode = await union.updateHongBaoSetting(msg.status, msg.startTime, msg.endTime, msg.count, msg.totalScore);
        next(null, {
            code: resCode
        });
    } catch (e) {
        logger.error(e.stack);
        next(null, {
            code: 500
        });
    }
};

Handler.prototype.updateLotteryStatus = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });

    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }
    await union.updateLotteryStatus(msg.isOpen);
    next(null, {
        code: code.OK,
    });
};

//新增修改联盟的抽水模式
Handler.prototype.UpdatePumpWaterPattern = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid()) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }
    await union.UpdatePumpWaterPattern(msg.pumpWaterPattern);
    next(null, {
        code: code.OK,
        msg: {
            unionInfo: union.getUnionInfo(session.uid)
        }
    });
};

//新增修改联盟的服务费
Handler.prototype.updateUnionServerScore = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID || !msg.serverScore) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid()) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }
    let serverScore = parseInt(msg.serverScore);
    await union.updateUnionServerScore(serverScore);
    next(null, {
        code: code.OK,
        msg: {
            unionInfo: union.getUnionInfo(session.uid),
            roomList: union.getUnionRoomList()
        }
    });
};

//新增设置联盟牌桌排序
Handler.prototype.updateUnionTableSort = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid()) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }
    await union.updateUnionTableSort(msg.unionID, msg.tableSort);
    next(null, {
        code: code.OK,
        msg: {
            tableSort: msg.tableSort
        }
    });
};

//新增设置联盟牌桌颜色
Handler.prototype.updateUnionTableColor = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    //  let union = await unionManager.getUnion(msg.unionID);
    //  if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
    //      next(null, { code: code.PERMISSION_NOT_ENOUGH });
    //      return;
    //  }
    let userData = await userDao.getUserDataByUid(session.uid);
    let unionInfoItem = userData.unionInfo.find(function (ele) {
        return ele.unionID === msg.unionID;
    });

    //是否在联盟中
    if (!unionInfoItem) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }

    //是否是盟主或者管理员
    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }

    if (msg.tableColor == null || msg.tableColor == undefined) {
        msg.tableColor = 0;
    }
    if (msg.unionBg == null || msg.unionBg == undefined) {
        msg.unionBg = 0;
    }
    if (msg.tableStyle == null || msg.tableStyle == undefined) {
        msg.tableStyle = 0;
    }
    await union.updateUnionTableColor(msg.unionID, msg.tableColor, msg.unionBg, msg.tableStyle);
    next(null, {
        code: code.OK,
        msg: {
            tableColor: msg.tableColor,
            unionBg: msg.unionBg,
            tableStyle: msg.tableStyle
        }
    });
};
//删除联盟
Handler.prototype.deleteUnion = async function (msg, session, next) {
    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    let union = await unionManager.getUnion(msg.unionID);
    if (session.uid !== union.getOwnerUid()) {
        next(null, {
            code: code.PERMISSION_NOT_ENOUGH
        });
        return;
    }
    //解散机器人人
    await commonDao.updateData('userModel', { "unionID": msg.unionID, 'isRobot': true }, { unionID: 0 });
    await union.deleteUnion();
    next(null, {
        code: code.OK,
        msg: {
            unionInfo: union.getUnionInfo(session.uid)
        }
    });
};


//新增修改联盟信息
Handler.prototype.updateUnionInfo = async function (msg, session, next) {

    if (!session.uid) {
        next(null, {
            code: code.INVALID_UERS
        });
        return;
    }
    if (!msg.unionID || !msg.unionInfo) {
        next(null, {
            code: code.REQUEST_DATA_ERROR
        });
        return;
    }
    try {

        let userData = await userDao.getUserDataByUid(session.uid);
        let unionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });


        //是否在联盟中
        if (!unionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        //是否是盟主或者管理员
        let union = await unionManager.getUnion(msg.unionID);
        if (session.uid !== union.getOwnerUid() && !unionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        let updateInfo = {
            resultLotteryInfo: {},
            hongBaoInfo: {}
        };

        //游戏限制
        if (msg.unionInfo.gameLimited != undefined) {
            updateInfo.gameLimited = msg.unionInfo.gameLimited || 0;
        }

        //服务费
        if (msg.unionInfo.unionFee != undefined) {
            updateInfo.serverScore = msg.unionInfo.unionFee || 0;
        }
        //联盟打烊
        if (msg.unionInfo.unionOpen != undefined) {
            updateInfo.opening = msg.unionInfo.unionOpen || false;
        }
        if (msg.unionInfo.hbStart != undefined) {
            //开始时间和结束时间
            updateInfo.hongBaoInfo.startTime = msg.unionInfo.hbStart || 0;
        }
        if (msg.unionInfo.hbStart != undefined) {
            //开始时间和结束时间
            updateInfo.hongBaoInfo.endTime = msg.unionInfo.hbEnd || 0;
        }
        if (msg.unionInfo.hbCount != undefined) {
            //开始时间和结束时间
            updateInfo.hongBaoInfo.count = msg.unionInfo.hbCount || 0;
        }
        if (msg.unionInfo.hbTotal != undefined) {
            //开始时间和结束时间
            updateInfo.hongBaoInfo.totalScore = msg.unionInfo.hbTotal || 0;
        }
        //是否开启抽奖
        if (msg.unionInfo.hbOpen != undefined) {
            updateInfo.resultLotteryInfo.status = msg.unionInfo.hbOpen || false;
        }
        //联盟公告
        if (msg.unionInfo.unionNotice != undefined) {
            updateInfo.notice = msg.unionInfo.unionNotice || "";
        }
        //联盟名称
        if (msg.unionInfo.unionName != undefined) {
            updateInfo.unionName = msg.unionInfo.unionName || 0;
        }
        //是否空桌
        if (msg.unionInfo.emptyTable != undefined) {
            updateInfo.emptyTable = msg.unionInfo.emptyTable;
        }
        //是否邀请
        if (msg.unionInfo.isInvite != undefined) {
            updateInfo.isInvite = msg.unionInfo.isInvite;
        }
        //满桌上限
        if (msg.unionInfo.fullTableLimit != undefined) {
            updateInfo.fullTableLimit = msg.unionInfo.fullTableLimit || 0;
        }
        //解散申请次数
        if (msg.unionInfo.disApplyCount != undefined) {
            updateInfo.disApplyCount = msg.unionInfo.disApplyCount || 0;
        }
        //用户主动加入
        if (msg.unionInfo.inviteLimit != undefined) {
            updateInfo.inviteLimit = msg.unionInfo.inviteLimit || false;
        }
        //进圈审核
        if (msg.unionInfo.joinVerify != undefined) {
            updateInfo.joinVerify = msg.unionInfo.joinVerify || false;
        }
        //禁用道具
        if (msg.unionInfo.propsLimit != undefined) {
            updateInfo.propsLimit = msg.unionInfo.propsLimit || false;
        }
        //隐藏桌子
        if (msg.unionInfo.tableHideCount != undefined) {
            updateInfo.tableHideCount = msg.unionInfo.tableHideCount || 0;
        }
        //不准备玩家解散
        if (msg.unionInfo.unReadyKick != undefined) {
            updateInfo.unReadyKick = msg.unionInfo.unReadyKick || 0;
        }
        //同组禁入
        if (msg.unionInfo.groupLimit != undefined) {
            updateInfo.groupLimit = msg.unionInfo.groupLimit || false;
        }
        //解散类型
        if (msg.unionInfo.dismissType != undefined) {
            updateInfo.dismissType = msg.unionInfo.dismissType || 0;
        }
        //排行榜
        if (msg.unionInfo.showRank != undefined) {
            updateInfo.showRank = msg.unionInfo.showRank || false;
        }
        //桌子排序
        if (msg.unionInfo.tableSort != undefined) {
            updateInfo.tableSort = msg.unionInfo.tableSort || 0;
        }

        if (msg.unionInfo.isTeamData != undefined) {
            updateInfo.isTeamData = msg.unionInfo.isTeamData;
        }

        if (msg.unionInfo.isUserData != undefined) {
            updateInfo.isUserData = msg.unionInfo.isUserData;
        }


        if (msg.unionInfo.isScoreData != undefined) {
            updateInfo.isScoreData = msg.unionInfo.isScoreData;
        }

        let resCode = await union.updateUnionInfo(updateInfo);

        let recordArr = await userInfoServices.getUserUnions(userData);

        next(null, {
            code: resCode,
            updateUserData: {
                userUnions: recordArr,
                unionInfo: userData.unionInfo
            },
            msg: {
                unionInfo: union.getUnionInfo(session.uid)
            }
        });

    } catch (e) {
        logger.error(e.stack);
        next(null, {
            code: 500
        });
    }
};


//获取玩家当前桌子的抽水设置 getUserRate
Handler.prototype.getUserRate = async function (msg, session, next) {

    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }

    if (!msg.unionID || !msg.uid) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        return;
    }

    try {

        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        let gameRuleID = msg.gameRuleID;
        let union = await unionManager.getUnion(msg.unionID);
        let curRebateRate = 0;
        let curFixRate = 0;
        let curTicketRate = 0;

        if (session.uid == union.unionData.ownerUid) {
            curRebateRate = 1;
            curFixRate = 1;
            curTicketRate = 1;
        } else {
            let curRecord = await commonDao.findOneData('unionGameRateModel', { gameRuleID: gameRuleID, uid: session.uid });
            let userUnionInfoItem = userData.unionInfo.find(function (element) {
                return element.unionID === msg.unionID;
            });

            curRebateRate = curRecord ? curRecord.rebateRate : userUnionInfoItem.rebateRate;
            curFixRate = curRecord ? curRecord.fixRate : userUnionInfoItem.fixScoreRate;
            curTicketRate = curRecord ? curRecord.ticketRate : userUnionInfoItem.ticketRate;
        }

        let userCurData = await userDao.getUserDataByUid(msg.uid);
        if (!userCurData) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        let userUnionInfoItem = userCurData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        //玩家的比例
        let userRecord = await commonDao.findOneData('unionGameRateModel', { gameRuleID: gameRuleID, uid: msg.uid });
        let rebateRate = userRecord ? userRecord.rebateRate : userUnionInfoItem.rebateRate;
        let fixRate = userRecord ? userRecord.fixRate : userUnionInfoItem.fixScoreRate;
        let ticketRate = userRecord ? userRecord.ticketRate : userUnionInfoItem.ticketRate;

        next(null, { code: code.OK, curRebateRate, curFixRate, curTicketRate, rebateRate, ticketRate, fixScoreRate: fixRate });


    } catch (e) {
        logger.error(`[${session.uid}] getUserRate =` + e.stack);
        next(null, { code: 500 });
    }
};

//设置桌子的抽水setUserRate
Handler.prototype.setUserRate = async function (msg, session, next) {


    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }

    if (!msg.userList || !msg.gameRuleID || !msg.unionID) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        return;
    }

    try {

        let { gameRuleID, unionID, userList } = msg;
        for (let i = 0; i < userList.length; i++) {

            let rebateRate = userList[i].rebateRate;
            let fixRate = userList[i].fixScoreRate;
            let ticketRate = userList[i].ticketRate;
            let uid = userList[i].uid;
            let superUID = session.uid;
            let saveData = { rebateRate, fixRate, gameRuleID, ticketRate, unionID, superUID, uid };
            let curData = await commonDao.findOneAndUpdateEx('unionGameRateModel', { unionID, gameRuleID, superUID, uid }, saveData, { new: true, upsert: true });
        }
        next(null, { code: code.OK });

    } catch (e) {
        logger.error(`[${session.uid}] setUserRate =` + e.stack);
        next(null, { code: 500 });
    }
};
